import axios from 'axios'
// import router from 'umi/router'
const fetch = options => {
  const { method = 'get', data, fetchType, url } = options
  var token = window.sessionStorage.getItem('token')
  var headers = {
    Authorization: 'Bearer ' + token
  }
  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: data,
        headers
      })
    case 'delete':
      return axios.delete(url, {
        data: data,
        headers
      })
    case 'post':
      return url.includes('/login')
        ? axios.post(url, data)
        : axios.post(url, data, { headers })
    case 'put':
      return axios.put(url, data, { headers })
    case 'patch':
      return axios.patch(url, data, { headers })
    default:
      return axios(options)
  }
}

export default function request(options) {
  return fetch(options)
    .then(response => {
      const { statusText, status } = response
      const data = response.data

      if (response.data.token_status === false) {
        const source = window.sessionStorage.getItem('source')
        if (source === 'customer' || source === 'admin') {
          // window.location.pathname = "tecloud.html";
        } else {
          // const loginLocal = window.sessionStorage.getItem("loginLocal");
          // const url = response.data.logout_url;
          // if (loginLocal !== "true" && url) {
          //   window.location.replace(url);
          //   return;
          // }
          // router.push({
          //   pathname: '/login'
          // })
        }
      }
      return Promise.resolve({
        success: true,
        message: statusText,
        statusCode: status,
        ...data
      })
    })
    .catch(error => {
      const { response } = error
      let msg
      let statusCode
      if (response && response instanceof Object) {
        const { data, statusText, token_status } = response
        statusCode = response?.status
        msg = data?.message || statusText
      } else {
        statusCode = 600
        msg = error.message || 'Network Error'
      }

      /* eslint-disable */
      return Promise.reject({ success: false, statusCode, message: msg });
    });
}
